import { ref, computed, watch } from 'vue'
import type { PropertyPanelProps } from '../types'
import Modeling from 'bpmn-js/lib/features/modeling/Modeling.js'
import type { Moddle } from 'bpmn-moddle'

export interface MultiInstanceConfig {
  isSequential: boolean // true: 依次审批, false: 会签
  completionCondition: string // 完成条件
}

export function useMultiInstanceConfig(props: PropertyPanelProps) {
  // 是否开启会签
  const isMultiInstance = ref(false)

  // 会签配置
  const multiInstanceConfig = ref<MultiInstanceConfig>({
    isSequential: false,
    completionCondition: '${ nrOfCompletedInstances >= nrOfInstances }',
  })

  // 会签流程变量说明
  const multiInstanceVariables = [
    { name: 'nrOfInstances', desc: '会签总数' },
    { name: 'nrOfCompletedInstances', desc: '已完成的会签数量' },
    { name: 'nrOfActiveInstances', desc: '当前活动的会签数量' },
    { name: 'loopCounter', desc: '当前会签的索引（从0开始）' },
  ]

  // 是否显示会签配置
  const showMultiInstance = computed(() => {
    if (!props.currentElement) return false
    return props.currentElement.type === 'bpmn:UserTask'
  })

  // 监听元素变化，同步会签状态
  watch(
    () => props.currentElement,
    (element) => {
      if (!element) return
      const loopCharacteristics = element.businessObject.loopCharacteristics
      // 更新会签开关状态
      isMultiInstance.value = !!loopCharacteristics

      if (loopCharacteristics) {
        multiInstanceConfig.value = {
          isSequential: loopCharacteristics.isSequential || false,
          completionCondition:
            loopCharacteristics.completionCondition?.body ||
            '${ nrOfCompletedInstances >= nrOfInstances }',
        }
      } else {
        // 重置配置
        multiInstanceConfig.value = {
          isSequential: false,
          completionCondition: '${ nrOfCompletedInstances >= nrOfInstances }',
        }
      }
    },
    { immediate: true },
  )

  // 更新会签配置
  const updateMultiInstance = (config: MultiInstanceConfig) => {
    const { modeler, currentElement } = props
    if (!modeler || !currentElement) return

    const modeling = modeler.get('modeling') as Modeling
    const moddle = modeler.get('moddle') as Moddle

    // 创建或更新多实例特性
    const loopCharacteristics = moddle.create('bpmn:MultiInstanceLoopCharacteristics', {
      isSequential: config.isSequential,
    })

    // 设置完成条件
    const completionCondition = moddle.create('bpmn:FormalExpression', {
      body: config.completionCondition,
    })
    loopCharacteristics.completionCondition = completionCondition

    // 更新元素
    modeling.updateProperties(currentElement, {
      loopCharacteristics: loopCharacteristics,
    })
  }

  // 移除会签配置
  const removeMultiInstance = () => {
    const { modeler, currentElement } = props
    if (!modeler || !currentElement) return

    const modeling = modeler.get('modeling') as Modeling
    modeling.updateProperties(currentElement, {
      loopCharacteristics: null,
    })
  }

  // 处理会签配置变更
  const handleMultiInstanceChange = (value: boolean) => {
    isMultiInstance.value = value
    if (value) {
      // 开启会签，使用默认配置
      updateMultiInstance({
        isSequential: false,
        completionCondition: '${ nrOfCompletedInstances >= nrOfInstances }',
      })
    } else {
      // 关闭会签
      removeMultiInstance()
    }
  }

  // 处理会签配置更新
  const handleMultiInstanceUpdate = () => {
    if (isMultiInstance.value) {
      updateMultiInstance(multiInstanceConfig.value)
    }
  }

  return {
    showMultiInstance,
    isMultiInstance,
    multiInstanceConfig,
    multiInstanceVariables,
    handleMultiInstanceChange,
    handleMultiInstanceUpdate,
  }
}
